import Header from "@/components/Header"
import s from "./styles.module.less"
import { useNavigate, useSearchParams } from "react-router-dom"
import { useEffect, useRef, useState } from "react"
import { deleteDetailApi, getDetailApi } from "@/apis"
import IconFont from "@/components/CustomIcon"
import { typeMap } from "@/utils"
import classNames from "classnames"
import dayjs from "dayjs"
import { Modal, Toast } from "antd-mobile"
import PopupAddBill from "@/components/PopupAddBill"

function Detail() {
  const [searchParams] = useSearchParams()
  const paramValue = searchParams.get("id")
  const [detail, setDetail] = useState({})
  const navigate = useNavigate()
  const editRef = useRef()

  const getDetail = async () => {
    const { data } = await getDetailApi(paramValue)
    setDetail(data.data)
  }

  useEffect(() => {
    getDetail()
  }, [])

  const deleteDetail = async (id) => {
    const result = await Modal.confirm({
      title: "删除",
      content: "确认删除账单？",
    })
    if (result) {
      const response = deleteDetailApi({ id })
      Toast.show("删除成功")
      navigate(-1)
    }
  }

  return (
    <div className={s.detail}>
      <Header title="账单详情"></Header>
      <div className={s.card}>
        <div className={s.type}>
          <span
            className={classNames({
              [s.iconfont]: true,
              [s.expense]: detail.pay_type === 1,
              [s.income]: detail.pay_type === 2,
            })}
          >
            <IconFont
              type={detail.type_id ? typeMap[detail.type_id].icon : 1}
            ></IconFont>
          </span>
          <span>{detail.type_name || ""}</span>
        </div>
        {detail.pay_type === 1 ? (
          <div className={s.amount}>-{detail.amount}</div>
        ) : (
          <div className={s.amount}>+{detail.amount}</div>
        )}
        <div className={s.info}>
          <div className={s.time}>
            <span>记录时间</span>
            <span>{dayjs(Number(detail.date)).format("YYYY-MM-DD HH:mm")}</span>
          </div>
          <div className={s.time}>
            <span>备注</span>
            <span>{detail.remark || "-"}</span>
          </div>
        </div>
        <div className={s.operation}>
          <span className={s.span} onClick={() => deleteDetail(detail.id)}>
            <IconFont type="shanchu"></IconFont>删除
          </span>
          <span
            className={s.span}
            onClick={() => editRef.current && editRef.current.showP()}
          >
            <IconFont type="tianjia"></IconFont>编辑
          </span>
        </div>
        <PopupAddBill
          ref={editRef}
          detail={detail}
          onReload={getDetail}
        ></PopupAddBill>
      </div>
    </div>
  )
}

export default Detail
